<!DOCTYPE html>
          <head>
        <meta charset="utf-8">
            
            <title>
                「Retrofit」0x04POST方式提交JSON数据 | ttdevs
            </title>
            <meta content="width=device-width, initial-scale=1" name="viewport">
            <meta name="theme-color" content="#4184f3">
            
            
            <link href="/favicon.ico" rel="icon"/>
            

            <link rel="stylesheet" href="/css/highlight.light.css">
            <link rel="stylesheet" href="/css/prism-customize.css">
            <link rel="stylesheet" href="/css/nav-icon.css">
            <link rel="stylesheet" href="/css/waves.min.css">
            <link rel="stylesheet" href="/css/jquery.tocify.css">
            <link rel="stylesheet" href="/css/main.css">
            <link rel="stylesheet" href="/css/nav-indicator.css">
            
  

  
  <!-- 谷歌统计 -->
  <script>
    (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
    (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
    m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
    })(window,document,'script','//www.google-analytics.com/analytics.js','ga');

    ga('create', 'UA-97465173-1', 'auto');
    ga('send', 'pageview');

  </script>
  
            </meta>
        </meta>
    </head>

    <body>
        <header>
            <!-- cover image or sth. -->
        </header>
        <div id="main" class="m-scene">
            
<div class="nav-wrapper">

    <div class="container">
        <nav>
            <div class="logo wave">
                <a href="/" id="logo">
                    ttdevs
                </a>
            </div>
            <div class="nav-toggle-icon" >
                <div class="material-hamburger">
                    <span>
                    </span>
                    <span>
                    </span>
                    <span>
                    </span>
                </div>
            </div>
            <div class="menu-wrapper">
                <div class="nav-indicator">
                </div>
                <ul class="menus">
                    
                     
                        <li>
                            <a class="wave " href="/">
                                首页
                            </a>
                        </li>
                     
                        <li>
                            <a class="wave " href="/archives">
                                归档
                            </a>
                        </li>
                     
                        <li>
                            <a class="wave " href="/about">
                                关于
                            </a>
                        </li>
                     
                    
                   
                </ul>
            </div>
        </nav>
    </div>
</div>
            <div class="container content">
                <div class="scene_element scene_element--fadein">
                    <div class="row">
    <div class="main">
        <article>
          
          <header class="post-header with-cover" style="background-image:url('/1970/01/01/[Retrofit]0x04POST方式提交JSON数据/cover.jpg')" >
          
          </header>
          <h1 class="post-title">「Retrofit」0x04POST方式提交JSON数据</h1>

          <section class="post-info">
            <span class="post-date">1970/01/01</span>
            
            <span class="post-category">
                <a class="article-category-link" href="/categories/技术/">技术</a>
            </span>
            
            
            <span class="post-tags">
              <ul class="post-tag-list"><li class="post-tag-list-item"><a class="post-tag-list-link" href="/tags/Retrofit/">Retrofit</a></li></ul>
            </span>
            
          </section>

          <section class="post-content">
            <h2 id="0x00-HTTP-Method：POST"><a href="/1970/01/01/[Retrofit]0x04POST方式提交JSON数据/#0x00-HTTP-Method：POST" class="headerlink" title="0x00 HTTP Method：POST"></a>0x00 HTTP Method：POST</h2><p>POST请求再日常的使用中很常见，比如登录，上传数据中使用。之前介绍了GET方式，今天简单介绍下如何使用POST来提交数据。</p>
<h2 id="0x01-常用的POST方式"><a href="/1970/01/01/[Retrofit]0x04POST方式提交JSON数据/#0x01-常用的POST方式" class="headerlink" title="0x01 常用的POST方式"></a>0x01 常用的POST方式</h2><p>POST方式提交数据再浏览器中的表现主要是使用Form，在客户端中国中的主要表现是提交JSON数据。当然，具体是什么数据格式并不重要，我们可以通过抓包来分析：最终数据都是一样的。</p>
<h3 id="使用Model对象"><a href="/1970/01/01/[Retrofit]0x04POST方式提交JSON数据/#使用Model对象" class="headerlink" title="使用Model对象"></a>使用Model对象</h3><p>首先新建一个model对象，比如：User，添加常用的熟悉和get／set方法。新建我们的Service：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div></pre></td><td class="code"><pre><div class="line"><span class="meta">@POST</span>(<span class="string">"/send"</span>)</div><div class="line"><span class="function"><span class="keyword">public</span> Call&lt;ResponseBody&gt; <span class="title">modelPost</span><span class="params">(@Url String url, @Body User user)</span></span>;</div></pre></td></tr></table></figure>
<p>测试代码：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div><div class="line">30</div><div class="line">31</div><div class="line">32</div><div class="line">33</div><div class="line">34</div><div class="line">35</div></pre></td><td class="code"><pre><div class="line"><span class="meta">@Test</span></div><div class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">modelPost</span><span class="params">()</span> <span class="keyword">throws</span> Exception </span>&#123;</div><div class="line">   HttpLoggingInterceptor logging = <span class="keyword">new</span> HttpLoggingInterceptor();</div><div class="line">   logging.setLevel(HttpLoggingInterceptor.Level.BASIC);</div><div class="line"></div><div class="line">   OkHttpClient client = RetrofitManager.getClient(logging);</div><div class="line"></div><div class="line">   Retrofit retrofit = RetrofitManager.getRetrofit(client);</div><div class="line">   ExampleService service = retrofit.create(ExampleService.class);</div><div class="line"></div><div class="line">   String url = <span class="string">"http://www.remoteurl.com"</span>;</div><div class="line">   User user = <span class="keyword">new</span> User();</div><div class="line">   user.setName(<span class="string">"ttdevs"</span>);</div><div class="line">   Call&lt;ResponseBody&gt; example = service.modelPost(url, user);</div><div class="line"></div><div class="line">   <span class="keyword">final</span> CountDownLatch countDownLatch = <span class="keyword">new</span> CountDownLatch(<span class="number">1</span>);</div><div class="line">   example.enqueue(<span class="keyword">new</span> Callback&lt;ResponseBody&gt;() &#123;</div><div class="line">       <span class="meta">@Override</span></div><div class="line">       <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">onResponse</span><span class="params">(Call&lt;ResponseBody&gt; call, Response&lt;ResponseBody&gt; response)</span> </span>&#123;</div><div class="line">           <span class="keyword">try</span> &#123;</div><div class="line">               print(response.body().string());</div><div class="line">           &#125; <span class="keyword">catch</span> (IOException e) &#123;</div><div class="line">               e.printStackTrace();</div><div class="line">           &#125;</div><div class="line"></div><div class="line">           countDownLatch.countDown();</div><div class="line">       &#125;</div><div class="line"></div><div class="line">       <span class="meta">@Override</span></div><div class="line">       <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">onFailure</span><span class="params">(Call&lt;ResponseBody&gt; call, Throwable t)</span> </span>&#123;</div><div class="line">           countDownLatch.countDown();</div><div class="line">       &#125;</div><div class="line">   &#125;);</div><div class="line">   countDownLatch.await();</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<h3 id="使用RequestBody对象"><a href="/1970/01/01/[Retrofit]0x04POST方式提交JSON数据/#使用RequestBody对象" class="headerlink" title="使用RequestBody对象"></a>使用RequestBody对象</h3><p>这里我们来提交一份JSON数据，首先还是再Service中创建一个方法：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div></pre></td><td class="code"><pre><div class="line"><span class="meta">@POST</span>(<span class="string">"/send"</span>)</div><div class="line"><span class="function"><span class="keyword">public</span> Call&lt;ResponseBody&gt; <span class="title">withRequestBody</span><span class="params">(@Url String url, @Body RequestBody body)</span></span>;</div></pre></td></tr></table></figure>
<p>再接着创建我们的请求：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div><div class="line">30</div><div class="line">31</div><div class="line">32</div><div class="line">33</div><div class="line">34</div><div class="line">35</div><div class="line">36</div><div class="line">37</div><div class="line">38</div><div class="line">39</div><div class="line">40</div><div class="line">41</div></pre></td><td class="code"><pre><div class="line"><span class="meta">@Test</span></div><div class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">withRequestBody</span><span class="params">()</span> <span class="keyword">throws</span> Exception </span>&#123;</div><div class="line">    HttpLoggingInterceptor logging = <span class="keyword">new</span> HttpLoggingInterceptor();</div><div class="line">    logging.setLevel(HttpLoggingInterceptor.Level.BASIC);</div><div class="line"></div><div class="line">    OkHttpClient client = RetrofitManager.getClient(logging);</div><div class="line"></div><div class="line">    Retrofit retrofit = RetrofitManager.getRetrofit(client);</div><div class="line">    ExampleService service = retrofit.create(ExampleService.class);</div><div class="line"></div><div class="line">    String url = <span class="string">"http://www.remoteurl.com"</span>;</div><div class="line"></div><div class="line">    JSONObject result = <span class="keyword">new</span> JSONObject();</div><div class="line">    <span class="keyword">try</span> &#123;</div><div class="line">        result.put(<span class="string">"record"</span>, <span class="string">"hello"</span>);</div><div class="line">    &#125; <span class="keyword">catch</span> (JSONException e) &#123;</div><div class="line">        e.printStackTrace();</div><div class="line">    &#125;</div><div class="line">    RequestBody body = RequestBody.create(MediaType.parse(<span class="string">"application/json"</span>), result.toString());</div><div class="line">    Call&lt;ResponseBody&gt; example = service.withRequestBody(url, body);</div><div class="line"></div><div class="line">    <span class="keyword">final</span> CountDownLatch countDownLatch = <span class="keyword">new</span> CountDownLatch(<span class="number">1</span>);</div><div class="line">    example.enqueue(<span class="keyword">new</span> Callback&lt;ResponseBody&gt;() &#123;</div><div class="line">        <span class="meta">@Override</span></div><div class="line">        <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">onResponse</span><span class="params">(Call&lt;ResponseBody&gt; call, Response&lt;ResponseBody&gt; response)</span> </span>&#123;</div><div class="line">            <span class="keyword">try</span> &#123;</div><div class="line">                print(response.body().string());</div><div class="line">            &#125; <span class="keyword">catch</span> (IOException e) &#123;</div><div class="line">                e.printStackTrace();</div><div class="line">            &#125;</div><div class="line"></div><div class="line">            countDownLatch.countDown();</div><div class="line">        &#125;</div><div class="line"></div><div class="line">        <span class="meta">@Override</span></div><div class="line">        <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">onFailure</span><span class="params">(Call&lt;ResponseBody&gt; call, Throwable t)</span> </span>&#123;</div><div class="line">            countDownLatch.countDown();</div><div class="line">        &#125;</div><div class="line">    &#125;);</div><div class="line">    countDownLatch.await();</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<h2 id="0x02-总结"><a href="/1970/01/01/[Retrofit]0x04POST方式提交JSON数据/#0x02-总结" class="headerlink" title="0x02 总结"></a>0x02 总结</h2><p>第一种方法，我们需要为每一个请求的对象创建一个Model，如果你不想创建model则可以选择第二种方式，直接创建一个JSON字符串，然后提交即可。还是相当简答的。</p>
<p><img src="https://raw.githubusercontent.com/ttdevs/ttdevs.github.io/common/images/logo.png" alt="Create by ttdevs"></p>

          </section>
        </article>
        

       
        <div class="pager">
          
            <a class="post-prev pager-item" href="/1970/01/01/[Retrofit]0x03同步与异步请求/" >
              <strong class="article-nav-caption">上一篇</strong>
              <p class="post-nav-title">「Retrofit」0x03同步与异步请求</p>
            </a>
          
          
            <a class="post-next pager-item" href="/1970/01/01/[Java](==)与(equals)/">
              <strong class="article-nav-caption">下一篇</strong>
              <p class="post-nav-title">「Java」(==)与(equals)</p>
            </a>
          
        </div>
        

         <!-- comments -->
        <div class="comment-section">
  
    


</div>

    </div>
    
    <aside>
        <div id="toc">
        </div>
    </aside>
    
</div>

                </div>
            </div>
        </div>
        <footer class="footer">
    <p>由<a href="http://hexo.io/" target="_blank">Hexo</a>强力驱动，搭载<a href="https://github.com/wayou/hexo-theme-gstyle">gstyle</a>主题</p>
    <p>
        &copy; 2017 ttdevs
    </p>
</footer>
<script src="/lib/jquery.js"></script>
<script src="/lib/waves.js"></script>
<script src="/lib/jquery-ui.js"></script>
<script src="/lib/jquery.tocify.js"></script>
<script src="/js/main.js"></script>

    </body>
</html>
